﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using TranslaterFromJson.Model;

namespace TranslaterFromJson.ViewModel;

public class MainWindowViewModel:ObservableObject
{
    string jsonFilePath;
    int currentItemNumb=0, totalItemsNumb=0;
    string keyText;
    string currentRefType,refText;List<string> refTypes;
    string currentTargetType, targetText;List<string> targetTypes;
    string status="就绪";
    string addLangType;

    JsonOperator JsonOperator;

    public string JsonFilePath
    {
        get => jsonFilePath; set
        {
            SetProperty(ref jsonFilePath, value);
            FilePathChangedHandler();
        }
    }
    public int CurrentItemNumb
    {
        get => currentItemNumb; set
        {
            SetProperty(ref currentItemNumb, value);
            //设置页码的功能
            showItem(currentItemNumb - 1);
            
        }
    }
    public int TotalItemsNumb { get => totalItemsNumb; set=> SetProperty(ref totalItemsNumb, value); }
    public string KeyText { get => keyText; set =>SetProperty(ref keyText , value); }
    public string CurrentRefType { get => currentRefType; set{ SetProperty(ref currentRefType, value);
            //切换参考语种
            RefTypeChangedHandler();
        } }



    public string RefText { get => refText; set =>SetProperty(ref refText , value); }
    public List<string> RefTypes { get => refTypes; set =>SetProperty(ref refTypes , value); }
    public string CurrentTargetType { get => currentTargetType; set { SetProperty(ref currentTargetType, value); 
        //切换翻译语种
        TargetTypeChangedHandler();
        } }
    public string TargetText { get => targetText; set { SetProperty(ref targetText, value); saveChangedTargetText(); } }
    public List<string> TargetTypes { get => targetTypes; set => SetProperty(ref targetTypes, value); }
    public string Status { get => status; set => SetProperty(ref status, value); }
    public string AddLangType { get => addLangType; set => SetProperty(ref addLangType, value); }

    private RelayCommand<string> onCopyCommand;
    public RelayCommand<string> OnCopyCommand =>
        onCopyCommand ??= new RelayCommand<string>((item) =>
        {
            switch (item)
            {
                case "keyText":
                    Clipboard.SetText(KeyText);Status = "复制了key值"; break;
                case "refText":
                    Clipboard.SetText(RefText); Status = "复制了参考翻译"; break;
                case "targetText":
                    Clipboard.SetText(TargetText); Status = "复制了键入翻译"; break;
                default:
                    break;
            }
        });
    private RelayCommand onBroswerFileCommand;
    public RelayCommand OnBroswerFileCommand =>
        onBroswerFileCommand ??= new RelayCommand(() =>
        {
            OpenFileDialog ofd=new OpenFileDialog();
            ofd.Filter = "json|*.Json";
            if (ofd.ShowDialog()==true)
            {
                JsonFilePath = ofd.FileName;
                ///载入json文件
            }

        });
    private RelayCommand onLastCommand;
    public RelayCommand OnLastCommand =>
        onLastCommand ??= new RelayCommand(() =>
        {
            //上一个
            CurrentItemNumb--;
            if (CurrentItemNumb<=0)
            {
                CurrentItemNumb = 1;
            }
            showItem(CurrentItemNumb-1);
            Status = "就绪";
        });

    private RelayCommand onNextCommand;
    public RelayCommand OnNextCommand =>
        onNextCommand ??= new RelayCommand(() =>
        {
            //下一个
            CurrentItemNumb++;
            if(CurrentItemNumb>=JsonOperator.JsonDataset.Count)
            {
                CurrentItemNumb = JsonOperator.JsonDataset.Count - 1;
            }
            showItem(CurrentItemNumb-1);
            Status = "就绪";
        });
    private RelayCommand onNextNotTransCommand;
    public RelayCommand OnNextNotTransCommand =>
        onNextNotTransCommand ??= new RelayCommand(() =>
        {
            //下一个没有翻译的
            JsonOperator.setCurrentNum(CurrentItemNumb - 1);
            if (CurrentTargetType!=string.Empty)
            {
                int temp = JsonOperator.getNextNotTransIndex(CurrentTargetType);
                showItem(temp);
                CurrentItemNumb = temp + 1;
            }
            else
            {
                Status = "请先选择或输入翻译的语言";
            }
            Status = "就绪";
        });
    private RelayCommand onSaveCommand;
    public RelayCommand OnSaveCommand =>
        onSaveCommand ??= new RelayCommand(() =>
        {
            //保存
            JsonOperator.save();
        });


    private RelayCommand onFilePathChangeCommand;
    public RelayCommand OnFilePathChangeCommand =>
        onFilePathChangeCommand ??= new RelayCommand(() =>
        {
            JsonOperator = new JsonOperator(JsonFilePath);
            if (JsonOperator.JsonDataset.Count == 0) { Status = "未能解析json格式"; }
            else
            {
                showItem(0);
            }
        });

    private RelayCommand onAddLangNameCommand;
    public RelayCommand OnAddLangNameCommand =>
        onAddLangNameCommand ??= new RelayCommand(() =>
        {
            if (AddLangType.Trim() != "")
            {
                if (isContainsTypeName(addLangType.Trim()))
                {
                    Status = "已存在同名项";
                    return;
                }
                TargetTypes.Add(AddLangType);
                SetProperty(ref targetTypes, targetTypes);
                Status = "添加成功";
            }
            else
            {
                Status = "不能添加空项";
            }
        });



    //public void FilePathChangedHandler(object sender, EventArgs e)
    //{
    //    JsonOperator = new JsonOperator(JsonFilePath);
    //    if (JsonOperator.JsonDataset.Count == 0) { status = "未能解析json格式"; }
    //    else
    //    {
    //        showItem(0);
    //    }
    //}



    private void FilePathChangedHandler()
    {
        JsonOperator = new JsonOperator(JsonFilePath);
        if (JsonOperator.JsonDataset==null) { Status = "未能解析json格式"; return; }
        else
        {
            CurrentItemNumb = 1;
            showItem(0);
            Status = string.Format("成功读取了{0}个词条", JsonOperator.JsonDataset.Count);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="index">第几个翻译的词条</param>
    private void showItem(int index)
    {
        if (index >= 0 && index < JsonOperator.JsonDataset.Count)
        {
            
            TotalItemsNumb = JsonOperator.JsonDataset.Count;
            KeyText = JsonOperator.JsonDataset[index].ItemName;
            RefTypes = getType(JsonOperator.JsonDataset[index].ItemNode);
            CurrentRefType = refTypes[0];
            int languageItemIndex = getLanguageTransTextFromItemName(CurrentRefType, JsonOperator.JsonDataset[index].ItemNode);
            if (languageItemIndex!=-1)
            {
                RefText = JsonOperator.JsonDataset[index].ItemNode[languageItemIndex].LangValue;
            }
            TargetTypes = getAllTypes();
            if(CurrentTargetType==null) CurrentTargetType= targetTypes[0];
            int languageTransItemIndex = getLanguageTransTextFromItemName(CurrentTargetType, JsonOperator.JsonDataset[index].ItemNode);
            try
            {
                TargetText = JsonOperator.JsonDataset[index].ItemNode[languageTransItemIndex].LangValue;
            }
            catch (Exception)
            {
                TargetText = "";
                Status = "翻译词条读取失败";
            }
            
        }
    }

    private List<string> getType(List< LanguageItem> items)
    {
        List<string> result = new List<string>();
        for (int i = 0; i < items.Count; i++)
        {
            result.Add(items[i].LangName);
        }
        return result;
    }
    private List<string> getAllTypes()
    {
        return JsonOperator.AllTypes;
    }
    private int getLanguageTransTextFromItemName(string itemName,List<LanguageItem> languageItems)
    {
        for (int i = 0; i < languageItems.Count; i++)
        {
            if (itemName == languageItems[i].LangName)
            {
                return i;
            }
        }
        return -1;
    }
    private void RefTypeChangedHandler()
    {
        JsonOperator.CurrentNum = CurrentItemNumb - 1;
        int index = getLanguageTransTextFromItemName(CurrentRefType, JsonOperator.JsonDataset[CurrentItemNumb-1].ItemNode);
        RefText = JsonOperator.JsonDataset[CurrentItemNumb - 1].ItemNode[index].LangValue;

        Status = "就绪";
    }
    private void TargetTypeChangedHandler()
    {
        JsonOperator.CurrentNum = CurrentItemNumb - 1;
        try
        {
            int index = getLanguageTransTextFromItemName(CurrentTargetType, JsonOperator.JsonDataset[CurrentItemNumb-1].ItemNode);
            TargetText = JsonOperator.JsonDataset[CurrentItemNumb-1].ItemNode[index].LangValue;
            Status = "就绪";
        }
        catch (Exception)
        {
            TargetText = "";
        }
        
    }
    private void saveChangedTargetText()
    {
        try
        {
            if (TargetText != string.Empty || TargetText != null)
            {
                bool hasKeyFlag= JsonOperator.isContansName(CurrentTargetType, JsonOperator.JsonDataset[CurrentItemNumb - 1].ItemNode);
                if (hasKeyFlag) {
                    int index = getLanguageTransTextFromItemName(CurrentTargetType, JsonOperator.JsonDataset[CurrentItemNumb - 1].ItemNode);
                    JsonOperator.JsonDataset[CurrentItemNumb - 1].ItemNode[index].LangValue = TargetText;
                    Status = "词条已保存";
                }
                else
                {
                    LanguageItem li = new LanguageItem();
                    li.LangName = CurrentTargetType;
                    li.LangValue = TargetText;
                    JsonOperator.JsonDataset[CurrentItemNumb - 1].ItemNode.Add(li);
                    Status = "词条已保存";
                }
                
            }
            
        }
        catch (Exception)
        {

            throw;
        }
        
    }
    private bool isContainsTypeName(string name)
    {
        for (int i = 0; i < TargetTypes.Count; i++)
        {
            if (name == TargetTypes[i])
            {
                return true;
            }
        }
        return false;
    }
}
